package com.sfac.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Author:唐琳的爹
 * @BelongsProject:hqyj_springboot
 * @BelongsPackage:com.sfac.filter
 * @CreateTime:2022/8/22 11:13:08
 */
@WebFilter
@Slf4j
public class ParamFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("====doFilter==========");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        // 因为 HttpServletRequest 不能直接操作 parmeterMap.所以构建 Mapper 对象来进行操作
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
            // 重写 wrapper 对象的 getParameter 方法. 替换掉脏字符串
/*            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);
                return StringUtils.isNotBlank(value) ? value.replaceAll("fuck", "***") : "";
            }*/

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                if (values == null) {
                    return new String[]{};
                }
                return Arrays.asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck", "***"))
                        .toArray(String[]::new);
            }
        };


        filterChain.doFilter(wrapper,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
